import fs from 'fs/promises'
import path from 'path'
import { config } from '../../config/index.js'
import logger from '../../services/logger.js'
import { PDFProcessor } from './pdfProcessor.js'
import { TextProcessor } from './textProcessor.js'
import { DocxProcessor } from './docxProcessor.js'
import { ExcelProcessor } from './excelProcessor.js'
import { MarkdownProcessor } from './markdownProcessor.js'

// 处理器映射
const processors = {
  '.pdf': new PDFProcessor(),
  '.docx': new DocxProcessor(),
  '.doc': new DocxProcessor(),
  '.txt': new TextProcessor(),
  '.md': new MarkdownProcessor(),
  '.json': new TextProcessor(),
  '.xlsx': new ExcelProcessor(),
  '.xls': new ExcelProcessor()
}

/**
 * 处理文件内容
 * @param {string} filePath - 文件路径
 * @returns {Promise<string>} - 处理后的文本内容
 */
export async function processFile(filePath) {
  try {
    logger.info('Processing file:', { path: filePath })
    
    // 尝试读取元数据文件获取文件类型
    let fileType = ''
    try {
      const metaPath = `${filePath}.meta.json`
      const metaContent = await fs.readFile(metaPath, 'utf-8')
      const meta = JSON.parse(metaContent)
      fileType = meta.type || ''
    } catch (error) {
      logger.warn('Failed to read metadata, will try to determine file type from path:', {
        path: filePath,
        error: error.message
      })
    }
    
    // 如果元数据中有类型，转换为扩展名格式
    let ext = fileType ? `.${fileType.toLowerCase()}` : path.extname(filePath).toLowerCase()
    
    // 获取对应的处理器
    const processor = processors[ext] || new TextProcessor()
    
    // 使用处理器处理文件
    const cleanedContent = await processor.process(filePath)

    logger.info('File processed:', {
      type: ext,
      path: filePath,
      contentLength: cleanedContent.length
    })

    return cleanedContent
  } catch (error) {
    logger.error('Failed to process file:', {
      path: filePath,
      error: error.message,
      stack: error.stack
    })
    throw error
  }
}

/**
 * 检查文件类型是否支持
 * @param {string} filename - 文件名
 * @returns {object} - 包含有效性和类型的对象
 */
export function checkFileType(filename) {
  const ext = path.extname(filename).toLowerCase()
  const allowedTypes = Object.keys(processors)
  
  return {
    valid: allowedTypes.includes(ext),
    type: ext.slice(1) || 'unknown'
  }
}

/**
 * 保存上传的文件
 * @param {object} file - 上传的文件对象
 * @returns {Promise<string>} - 保存后的文件路径
 */
export async function saveUploadedFile(file) {
  try {
    const uploadDir = config.server.upload.dir
    await fs.mkdir(uploadDir, { recursive: true })

    const filePath = path.join(uploadDir, file.filename)
    await fs.writeFile(filePath, file.buffer)

    logger.info('File saved:', {
      name: file.filename,
      size: file.size,
      path: filePath
    })

    return filePath
  } catch (error) {
    logger.error('Failed to save file:', {
      name: file.filename,
      error: error.message
    })
    throw error
  }
}

// 导出所有处理器，方便直接使用
export {
  PDFProcessor,
  TextProcessor,
  DocxProcessor,
  ExcelProcessor,
  MarkdownProcessor
} 